package com.mrjoew.weekend.web.api;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Christopher Jones
 * @ClassName LogoutApiController
 * @explain
 * @date 2020/9/7 0007 16:44
 */
@Api(tags = "登出")
@Slf4j
@RestController
public class LogoutApiController {

    private final TokenStore tokenStore;

    @Autowired
    public LogoutApiController(RedisConnectionFactory redisConnectionFactory) {
        this.tokenStore = new RedisTokenStore(redisConnectionFactory);
    }

    @ApiOperation("登出")
    @DeleteMapping("/oauth/logout")
    public boolean logout(String token) {
        try {
            OAuth2AccessToken oAuth2AccessToken = tokenStore.readAccessToken(token);
            if (oAuth2AccessToken != null) {
                tokenStore.removeAccessToken(oAuth2AccessToken);
                OAuth2RefreshToken oAuth2RefreshToken = oAuth2AccessToken.getRefreshToken();
                tokenStore.removeRefreshToken(oAuth2RefreshToken);
                tokenStore.removeAccessTokenUsingRefreshToken(oAuth2RefreshToken);
            }
            return true;
        } catch (Exception e) {
            log.error("Logout Failed! Token: {}", token, e);
            return false;
        }
    }
}
